using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data.Objects.SqlClient;
using System.Web.Security;
using System.Web.Profile;


using CooWork.Models;
using Coowork.Data.Mapping;


namespace CooWork.Controllers
{   
    public class WatchlistController : BaseController
    {
        private CooWorkEntities context = new CooWorkEntities();


        [HttpPost]
        public JsonResult Jback(string ulist, int? taskId, int? departmentId)
        {
            if (!taskId.HasValue || string.IsNullOrWhiteSpace(ulist))
                return new JsonNetResult();

            SqlClass.JbackSql(ulist, taskId.Value);
            CooTask ct = context.CooTasks.Single(x => x.ID == taskId.Value);

            List<MembershipUser> dusers=new List<MembershipUser>();

            if (departmentId.HasValue)
            {
                var wlist = ct.CooWatchlists.Select(x => x.Observer.Value).ToList();
                dusers = Membership.GetAllUsers().Cast<MembershipUser>().Where(user => ((int)ProfileBase.Create(user.UserName, true)["DepartmentId"]) == departmentId).Where(x => !wlist.Contains((System.Guid)x.ProviderUserKey)).ToList();
            }


            // create the first list by using a specific "template" type.
            var cwlist = new[] { new { taskId = "", observer="",userName="" } }.ToList();
            cwlist.Clear();
            foreach (CooWatchlist cw in ct.CooWatchlists)
            {
                cwlist.Add(new { taskId = cw.TaskId.ToString(), observer = cw.Observer.Value.ToString(), userName = CacheSet.UserCache[cw.Observer.Value] });
            }           

            var result = new JsonNetResult
            {
                Data = new { cwlist, dusers },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;                  
        }

        [HttpPost]
        public JsonResult Jchange(string ulist, int? taskId, int? departmentId)
        {
            if (!taskId.HasValue||string.IsNullOrWhiteSpace(ulist)||!departmentId.HasValue)
                return new JsonNetResult();

            var arr=ulist.Split(',');
            CooTask ct = context.CooTasks.Single(x => x.ID == taskId.Value);
          
            var watchlist=(from w in context.CooWatchlists
                          where w.TaskId==taskId  // && (!context.CooTasks.Single(x => x.ID == taskId.Value).CooWatchlists.Any(y => y.Observer.Value == w.Observer.Value))
                          select w.Observer).ToList();

            foreach (string s in arr)
            {             
                var c = new CooWatchlist();
                c.Observer = new System.Guid(s);
                c.TaskId = taskId;
                if (!watchlist.Contains(c.Observer))
                {
                    ct.CooWatchlists.Add(c);
                }
            }
            context.SaveChanges();          

            var wlist = ct.CooWatchlists.Select(x => x.Observer.Value).ToList();
            var dusers = Membership.GetAllUsers().Cast<MembershipUser>().Where(user => ((int)ProfileBase.Create(user.UserName, true)["DepartmentId"]) == departmentId).Where(x => !wlist.Contains((System.Guid)x.ProviderUserKey));

            var cwlist = new[] { new { taskId = "", observer = "", userName = "" } }.ToList();
            cwlist.Clear();
            foreach (CooWatchlist cw in ct.CooWatchlists)
            {
                cwlist.Add(new { taskId = cw.TaskId.ToString(), observer = cw.Observer.Value.ToString(), userName = CacheSet.UserCache[cw.Observer.Value] });
            }           
            
            var result = new JsonNetResult
            {
                Data =new {cwlist ,dusers},
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };

            return result;
        }


      

        //
        // GET: /Watchlist/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Watchlist/Create

      
        
     
        //
        // POST: /Watchlist/Edit/5

        [HttpPost]
        public ActionResult Edit(CooWatchlist coowatchlist)
        {
            if (ModelState.IsValid)
            {
                context.Entry(coowatchlist).State = EntityState.Modified;
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(coowatchlist);
        }

  

     

        protected override void Dispose(bool disposing)
        {
            if (disposing) {
                context.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}